<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/1/7
 * Time: 22:15
 */

namespace app\api\controller\v1;


use app\api\controller\BaseController;
use app\api\model\Express as ExpressModel;
use app\api\model\Order as OrderModel;
use app\api\service\Token as TokenService;
use app\api\service\Order as OrderService;
use app\api\validate\ExpressValidate;
use app\lib\enum\OrderStatusEnum;
use app\lib\enum\OrderTypeEnum;
use app\lib\Exception\OrderException;
use app\lib\Exception\SuccessNotice;
use app\lib\Exception\UserException;
use think\Db;
use think\Exception;

class Express extends BaseController
{
    protected $beforeActionList = [
        'checkOnlyUserScope' => ['only' => 'expressRecycle'],
        'checkSuperScope' => ['only' => 'expressBuy'],
    ];

    private function saveToExpress($orderID){
        $express = new ExpressModel();
        $express->order_id= $orderID;
        $express->comp_name= input('post.comp_name');
        $express->express_no= input('post.express_no');
        $express->save();
    }

    public function expressRecycle(){
        (new ExpressValidate())->toCheck();

        $orderID = input('post.order_id');
        $order = OrderModel::where('id','=', $orderID)->find();

        // 检查这个用户有没有这个权限
        $valid = TokenService::isValidateOperate($order->user_id);
        if(!$valid){
            throw new UserException([
                'info'=>'订单与用户不匹配',
                'errorCode'=> 80002
            ]);
        }

        // 检查 order的状态
        OrderService::checkOrderValid($orderID, OrderTypeEnum::Recycle, OrderStatusEnum::UNPAID);

        Db::startTrans();
        try{
            $this->saveToExpress($orderID);
            // prepay_id 暂存 from_id
            $order->prepay_id = input('post.form_id');
            $order->status = OrderStatusEnum::DELIVERED;
            $order->save();

            Db::commit();
        }
        catch (Exception $ex){
            Db::rollback();
            throw $ex;
        }

        throw new SuccessNotice();
    }


    public function expressBuy(){
        (new ExpressValidate())->toCheck();

        $orderID = input('post.order_id');

        $order = OrderModel::where('id','=', $orderID)->find();

        OrderService::checkOrderValid($orderID, OrderTypeEnum::Buy, OrderStatusEnum::PAID);

        Db::startTrans();
        try{
            $this->saveToExpress($orderID);
            $order->status = OrderStatusEnum::DELIVERED;
            $order->save();

            Db::commit();
        }
        catch (Exception $ex){
            Db::rollback();
            throw $ex;
        }

        throw new SuccessNotice();
    }

}